package com.untilov.gb.http;

import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class DataPumpMEImpl implements DataPumpIF {
    private Vector cookies;

    private String url;

    public DataPumpMEImpl(Vector cookies, String url) {
        this.cookies = cookies;
        this.url = url;
    }

    public InputStream getData() throws Exception {
        HttpConnection connection = (HttpConnection) Connector.open(url,
                Connector.READ_WRITE, true);
        prepareConnection(connection);
        addCookies(connection);
        return connection.openInputStream();
    }

    private void addCookies(HttpConnection connection) throws Exception {
        int cookiesSize = cookies.size();
        String cookiesPropertyValue = "";
        for (int i = 0; i < cookiesSize; i++) {
            // if not last cookie, separate with comma
            if (i != cookiesSize - 1) {
                cookiesPropertyValue += (cookies.elementAt(i) + ",");
            } else {
                cookiesPropertyValue += cookies.elementAt(i);
            }
        }
        if (cookiesSize > 0) {
            connection.setRequestProperty("Cookie", cookiesPropertyValue);
        }
    }

    private void prepareConnection(HttpConnection connection) throws Exception {
        connection.setRequestMethod("GET");
    }
}